import 'dart:math' as math;
import 'package:flutter/material.dart';
import 'package:flutter/material.dart' as W;
import 'package:flutter/rendering.dart';
import 'package:flutter_douban/config/Http_service.dart';
import 'package:flutter_douban/config/app_colors.dart';
import 'package:flutter_douban/main_page/store/view/store_shop_cell.dart';
import 'package:flutter_douban/main_page/store/view/store_shop_header.dart';
import 'package:flutter_douban/main_page/store/view/stroe_product_cell.dart';
import 'package:flutter_douban/model/store_category_model.dart';
import 'package:flutter_douban/tool_views/back_nav_btn.dart';
import 'package:flutter_douban/tool_views/nav_title_page.dart';
import 'package:flutter_douban/tool_views/stance_page.dart';

class StoreShopPage extends StatefulWidget {
  @override
  _StoreShopPageState createState() => _StoreShopPageState();
}

class _StoreShopPageState extends State<StoreShopPage>
    with SingleTickerProviderStateMixin {
  List<StoreCategoryModel> _storeList = StoreCategoryModelList([]).list;
  late StoreCategoryModel _model;
  String _select = '1';
  List _titleList = [
    {'name': '综合', 'id': '1'},
    {'name': '销量', 'id': '2'},
    {'name': '价格', 'id': '3'},
    {'name': '新品', 'id': '4'},
  ];

  Future _getListData() async {
    try {
      /// 全部数据
      Map<String, dynamic> result = await HttpService.getMockDataWithPath(
          path: _select == '1'?'mock/store_shop_data.json':'mock/store_category_data0${_select}.json');
      StoreCategoryModelList storeModelList =
          StoreCategoryModelList.fromJson(result["result"]["ps"]);
      StoreCategoryModel storeCategoryModel =
          StoreCategoryModel.fromJson(result["result"]["s"]);
      setState(() {
        _storeList = storeModelList.list;
        _model = storeCategoryModel;
      });

      /// 结束加载状态
    } catch (e) {
      print(e);
    } finally {}
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    /// 列表数据
    _getListData();
  }

  List<Widget> _sliverBuilder(BuildContext context, bool innerBoxIsScrolled) {
    List<Widget> rowList = [];
    _titleList.forEach((element) {
      rowList.add(
        InkWell(
          child: Container(
            alignment: Alignment.center,
            width: MediaQuery.of(context).size.width / 4,
            height: 38,
            color: Colors.white,
            child: Text(
              element['name'],
              style: TextStyle(fontSize: 14, color: _select == element['id'] ? Colors.black : Colors.grey),
            ),
          ),
          onTap: (){
            setState(() {
              _select = element['id'];
              _getListData();
            });
          },
        ),
      );
    });

    return <Widget>[
      ///头部信息
      SliverPersistentHeader(
        delegate: GSYSliverHeaderDelegate(
          maxHeight: 265,
          minHeight: 265,
          vSync: this,
          snapConfig: FloatingHeaderSnapConfiguration(
            curve: Curves.bounceInOut,
            duration: const Duration(milliseconds: 10),
          ),
          child: StoreShopHeaderView(
            model: _model,
          ),
        ),
      ),
      SliverOverlapAbsorber(
        handle: NestedScrollView.sliverOverlapAbsorberHandleFor(context),
        sliver: SliverPersistentHeader(
          pinned: true,

          /// SliverPersistentHeaderDelegate 的实现
          delegate: GSYSliverHeaderDelegate(
              maxHeight: 40,
              minHeight: 40,
              changeSize: true,
              vSync: this,
              snapConfig: FloatingHeaderSnapConfiguration(
                curve: Curves.bounceInOut,
                duration: const Duration(milliseconds: 10),
              ),
              builder: (BuildContext context, double shrinkOffset,
                  bool overlapsContent) {
                ///根据数值计算偏差
                var lr = 10 - shrinkOffset / 60 * 10;
                return Container(
                  alignment: Alignment.topCenter,
                  height: 40,
                  width: MediaQuery.of(context).size.width,
                  color: AppColors.page,
                  child: Row(
                    children: rowList,
                  ),
                );
              }),
        ),
      ),
    ];
  }

  @override
  Widget build(BuildContext context) {
    Widget widget;
    if (_storeList.length > 0) {
      widget = Container(
        child: NestedScrollView(
          physics: const AlwaysScrollableScrollPhysics(),
          headerSliverBuilder: _sliverBuilder,
          body: CustomScrollView(
            slivers: [
              W.Builder(
                builder: (context) {
                  return SliverOverlapInjector(
                      handle: NestedScrollView.sliverOverlapAbsorberHandleFor(
                          context));
                },
              ),
              SliverGrid(
                gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                  ///九宫格的列数
                  crossAxisCount: 2,

                  ///子Widget 宽与高的比值
                  childAspectRatio: 0.64,

                  ///主方向的 两个 子Widget 之间的间距
                  mainAxisSpacing: 1.0,

                  /// 次方向 子Widget 之间的间距
                  crossAxisSpacing: 1.0,
                ),

                ///子Item构建器
                delegate: new SliverChildBuilderDelegate(
                  (BuildContext context, num index) {
                    ///每一个子Item的样式
                    return StoreShopCell(
                      model: _storeList[index.toInt()],
                      index: index.toInt(),
                    );
                  },

                  ///子Item的个数
                  childCount: _storeList.length,
                ),
              ),
            ],
          ),
        ),
      );
    } else {
      widget = StancePage();
    }
    return Scaffold(
      appBar: AppBar(
        leading: BackNavBtn(),
        title: NavTitlePage(
          titleStr: '店铺详情',
        ),
      ),
      body: widget,
    );
  }
}

///动态头部处理
class GSYSliverHeaderDelegate extends SliverPersistentHeaderDelegate {
  GSYSliverHeaderDelegate(
      {required this.minHeight,
      required this.maxHeight,
      required this.snapConfig,
      required this.vSync,
      this.child,
      this.builder,
      this.changeSize = false});

  final double minHeight;
  final double maxHeight;
  final Widget? child;
  final Builder? builder;
  final bool changeSize;
  final TickerProvider vSync;
  final FloatingHeaderSnapConfiguration snapConfig;
  AnimationController? animationController;

  @override
  double get minExtent => minHeight;

  @override
  double get maxExtent => math.max(maxHeight, minHeight);

  @override
  TickerProvider get vsync => vSync;

  @override
  Widget build(
      BuildContext context, double shrinkOffset, bool overlapsContent) {
    if (builder != null) {
      return builder!(context, shrinkOffset, overlapsContent);
    }
    return child!;
  }

  @override
  bool shouldRebuild(GSYSliverHeaderDelegate oldDelegate) {
    return true;
  }

  @override
  FloatingHeaderSnapConfiguration get snapConfiguration => snapConfig;
}

typedef Widget Builder(
    BuildContext context, double shrinkOffset, bool overlapsContent);
